package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.product.domain.Category;
import com.spzx.product.mapper.CategoryMapper;
import com.spzx.product.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 商品分类 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-03-12
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Override
    public List<Category> treeSelect(Long parentId) {
        // 1. 根据父节点Id查询所有子节点
        List<Category> categoryList = baseMapper.selectList(new LambdaQueryWrapper<Category>().eq(Category::getParentId, parentId));
        // 2. 遍历所有子节点，判断是否有子节点，如果有，则递归查询所有子节点
        // 如果不为空
        if(!CollectionUtils.isEmpty(categoryList))
            for (Category category : categoryList) {
                // 便利集合 判断子节点是否还有子节点
                // 判断是否有子节点
                Long count = baseMapper.selectCount(new LambdaQueryWrapper<Category>().eq(Category::getParentId, category.getId()));
                category.setHasChildren(count > 0);
            }
        return categoryList;
    }
}
